﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Windows.Media.Animation;
using System.Runtime.InteropServices;
using CodeBuilder2.View.CB_UserControl.Content;

namespace CodeBuilder2.View.FloatWindow
{
    /// <summary>
    /// SimpleFloatWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SimpleFloatWindow : Window
    {

        #region 模拟系统窗体的标题栏（当前状态这部分代码并不会起作用，缺少 Window.Loaded 事件的委托）

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //添加一个消息过滤器
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_NCHITTEST)
            {
                // 获取屏幕坐标
                Point p = new Point();
                int pInt = lParam.ToInt32();
                p.X = (pInt << 16) >> 16;
                p.Y = pInt >> 16;
                if (IsOnTitleBar(PointFromScreen(p)))
                {
                    //欺骗系统鼠标点击在标题栏上
                    handled = true;
                    return new IntPtr(2);
                }
            }

            return IntPtr.Zero;
        }

        private bool IsOnTitleBar(Point p)
        {
            //假设标题栏在0和100之间
            if (p.Y >= 0 && p.Y < 100)
                return true;
            else
                return false;
        }

        private const int WM_NCHITTEST = 0x0084;

        #endregion

        public SimpleFloatWindow()
        {
            InitializeComponent();


            #region 用 Windows API 改变窗体大小
            // 因为还不熟练，这里先注释掉，窗体就暂时设定为不可改变大小
            //this.SourceInitialized += delegate(object sender, EventArgs e)
            //    {
            //        this._HwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
            //    };
            #endregion

        }

        public string ServerName { get; set; }
        public string DataBaseName { get; set; }

        private void sfWnd_Loaded(object sender, RoutedEventArgs e)
        {
            TableSelectContent tsc = new TableSelectContent() { ServerName = ServerName, DataBaseName = DataBaseName };
            //grdContainer.Children.Clear();
            Grid.SetRow(tsc, 1);
            grdContainer.Children.Add(tsc);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void tbkPanelName_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        private void tbkPanelName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //MessageBox.Show("haha");
        }

        private void sfWnd_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(tbkPanelName);
            if (this.Opacity < 1)
            {
                Storyboard sb = Resources["fadeOut"] as Storyboard;
                sb.Begin();
            }
        }

        private void Border_MouseMove(object sender, MouseEventArgs e)
        {
            Point p = e.GetPosition(this);
            //if (e.LeftButton != MouseButtonState.Pressed)
            //    this.Cursor = this.GetCursorByPosition(p);
            //if (Cursor == Cursors.Arrow)
            //{
            //    return;
            //}

            //if (e.LeftButton != MouseButtonState.Pressed)
            //    return;

            //border.CaptureMouse();            
            //double bThickness = this.border.BorderThickness.Top;
            //if (Cursor == Cursors.SizeWE)
            //{
            //    double newWidth = p.X + bThickness;
            //    if (newWidth > 0)
            //        this.Width = newWidth;
            //}
            //else if (Cursor == Cursors.SizeNS)
            //{
            //    double newHeight = p.Y + bThickness;
            //    if (newHeight > 0)
            //        this.Height = newHeight;
            //}            
            //else
            //{
            //    double newWidth = p.X + bThickness;
            //    double newHeight = p.Y + bThickness;

            //    if (newWidth > 0)
            //        this.Width = newWidth;
            //    if (newHeight > 0)
            //        this.Height = newHeight;
            //}
        }

        private void Border_MouseEnter(object sender, MouseEventArgs e)
        {
            //Point p = e.GetPosition(this);
            ////this.Cursor = this.GetCursorByPosition(p);
        }

        /*
        private const int WM_SYSCOMMAND = 0x112;
        private HwndSource _HwndSource;
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        private Dictionary<ResizeDirection, Cursor> cursors = new Dictionary<ResizeDirection, Cursor>
        {
            {ResizeDirection.Top, Cursors.SizeNS},
            {ResizeDirection.Bottom, Cursors.SizeNS},
            {ResizeDirection.Left, Cursors.SizeWE},
            {ResizeDirection.Right, Cursors.SizeWE},
            {ResizeDirection.TopLeft, Cursors.SizeNWSE},
            {ResizeDirection.BottomRight, Cursors.SizeNWSE},
            {ResizeDirection.TopRight, Cursors.SizeNESW},
            {ResizeDirection.BottomLeft, Cursors.SizeNESW}
        };

        private enum ResizeDirection
        {
            Left = 1,
            Right = 2,
            Top = 3,
            TopLeft = 4,
            TopRight = 5,
            Bottom = 6,
            BottomLeft = 7,
            BottomRight = 8,
        }
        */

        // 当鼠标离开（向边框外划出，不是向边框内内划出）时，回复鼠标的样式。(当前方法体为空）
        private void Border_MouseLeave(object sender, MouseEventArgs e)
        {
            // 后来测试了一下，这个光标值会自动恢复成默认的箭头状
            // 但是不排除，仍有个别情况会导致光标无法正常恢复，这里暂时不作处理，留待在日后使用中
            // 看看能否发现上述个别情况
            //this.Cursor = Cursors.Arrow;
        }

        /// <summary>
        /// 根据当前鼠标相对于本窗体的坐标判断该显示什么样子的光标
        /// </summary>
        /// <param name="mousePosition">相对于当前窗体的鼠标坐标值</param>
        /// <returns>代表用于鼠标指针的图像</returns>
        Cursor GetCursorByPosition(Point mousePosition)
        {
            Cursor c = null;
            double borderThickness = border.BorderThickness.Top;

            double right = this.ActualWidth - borderThickness;
            double bottom = this.ActualHeight - borderThickness;
            /*
            //ResizeDirection rd = ResizeDirection.BottomRight;
            // 在上下边框时
            if (mousePosition.X > borderThickness && mousePosition.X < right && mousePosition.Y < borderThickness)
                //c = Cursors.SizeNS;
                //rd = ResizeDirection.Top;
            if (mousePosition.X > borderThickness && mousePosition.X < right && mousePosition.Y > bottom)
                //c = Cursors.SizeNS;
                //rd = ResizeDirection.Bottom;

            // 在左右边框时
            if (mousePosition.Y > borderThickness && mousePosition.Y < bottom && mousePosition.X < borderThickness)
                //c = Cursors.SizeWE;
                //rd = ResizeDirection.Left;
            if (mousePosition.Y > borderThickness && mousePosition.Y < bottom && mousePosition.X > right)
                //c = Cursors.SizeWE;
                //rd = ResizeDirection.Right;

            // 在左上和右下角时（扩大角的范围定义）
            if (mousePosition.X < borderThickness && mousePosition.Y < borderThickness)
                //c = Cursors.SizeNWSE;
                //rd = ResizeDirection.TopLeft;
            if (mousePosition.X > right && mousePosition.Y > bottom)
                //c = Cursors.SizeNWSE;
                //rd = ResizeDirection.BottomRight;

            // 在右上和左下角时（扩大角的范围定义）
            if (mousePosition.X < borderThickness && mousePosition.Y > bottom)
                //c = Cursors.SizeNESW;
                //rd = ResizeDirection.BottomLeft;
            if (mousePosition.X > right && mousePosition.Y < borderThickness)
                //c = Cursors.SizeNESW;
                //rd = ResizeDirection.TopRight;
            //if (mousePosition.X > borderThickness + 20 && mousePosition.Y > borderThickness + 20 && mousePosition.X < right - 20 && mousePosition.Y < bottom - 20)
            //    c = Cursors.Arrow;

            //ResizeWindow(rd);
             */
            return c;
        }

        /*
        private void ResizeWindow(ResizeDirection direction)
        {
            SendMessage(_HwndSource.Handle, WM_SYSCOMMAND, (IntPtr)(61440 + direction), IntPtr.Zero);
        }
        */

        private void border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            border.ReleaseMouseCapture();
        }
    }
}
